<template>
  <div class="header">
    <!-- 折叠按钮 -->
    <div class="collapse-btn" @click="collapseChage">
      <el-icon v-if="sidebar.collapse">
        <Expand/>
      </el-icon>
      <el-icon v-else>
        <Fold/>
      </el-icon>
    </div>
    <div class="logo">{{ user.userInfo?.cityName }}车场管理系统</div>
    <div class="header-right">
      <div class="header-user-con">
        <!-- 消息中心 -->
        <!--				<div class="btn-bell" @click="router.push('/tabs')">-->
        <!--					<el-tooltip-->
        <!--						effect="dark"-->
        <!--						:content="message ? `有${message}条未读消息` : `消息中心`"-->
        <!--						placement="bottom"-->
        <!--					>-->
        <!--						<i class="el-icon-lx-notice"></i>-->
        <!--					</el-tooltip>-->
        <!--					<span class="btn-bell-badge" v-if="message"></span>-->
        <!--				</div>-->
        <template v-if="user.userInfo?.username || user.userInfo?.userId">
          <!-- 用户头像 -->
          <el-avatar class="user-avator" :size="30" :src="imgurl"/>
          <!-- 用户名下拉菜单 -->
          <el-dropdown class="user-name" trigger="click"
                       @command="handleCommand">
					<span class="el-dropdown-link">
            {{ user.userInfo.username }}
						<el-icon class="el-icon--right">
							<arrow-down/>
						</el-icon>
					</span>
            <template #dropdown>
              <el-dropdown-menu style="padding:5px 0 0 0" v-permiss="['superAdmin']">
                <el-dropdown-item command="changePWD">修改密码</el-dropdown-item>
              </el-dropdown-menu>
              <el-dropdown-menu>
                <el-dropdown-item command="loginout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <el-button v-else type="info" disabled link>暂未登录</el-button>
      </div>
    </div>

    <el-dialog
        destroy-on-close
        title="修改管理员密码（请谨慎操作）"
        v-model="dialogFormVisible"
        width="50%"
        draggable
    >
      <el-form
          label-width="auto"
          ref="ruleFormRef"
          :model="passwordForm"
          :rules="rules"
      >
        <el-form-item label="输入原密码" prop="pass">
          <el-input v-model="passwordForm.pass" autocomplete="off" type="password"/>
        </el-form-item>
        <el-form-item label="输入新密码" prop="newPass">
          <el-input v-model="passwordForm.newPass" autocomplete="off" type="password"/>
        </el-form-item>
        <el-form-item label="确认新密码" prop="reNewPass">
          <el-input v-model="passwordForm.reNewPass" autocomplete="off" type="password"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveItem(ruleFormRef)">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import {onMounted, ref, reactive} from 'vue';
import {useSidebarStore} from '../store/sidebar';
import {useRouter} from 'vue-router';
import {useUserStore} from "@/store/user";
import {UserApi} from "@/api";
import imgurl from '../assets/img/img.jpg';

import {useCookies} from "vue3-cookies";
import {ElMessage, FormInstance, FormRules} from "element-plus";

const {cookies} = useCookies();

const user = useUserStore();
const loginurl = cookies.get('loginurl') || user.userInfo.loginurl;
const username: string | null = localStorage.getItem('ms_username');
const message: number = 2;

const sidebar = useSidebarStore();
// 侧边栏折叠
const collapseChage = () => {
  sidebar.handleCollapse();
};

onMounted(() => {
  if (document.body.clientWidth < 1500) {
    collapseChage();
  }
});

const dialogFormVisible = ref(false);
const passwordForm = reactive({
  username: user.userInfo.username,
  pass: '',
  newPass: '',
  reNewPass: '',
})
const handleEditClear = () => {
  for (const key in passwordForm) {
    if (key === 'username') {
      passwordForm[key] = user.userInfo.username;
    } else {
      passwordForm[key] = '';
    }
  }
};
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  pass: [
    {required: true, message: '请输入原密码！', trigger: 'blur'},
  ],
  newPass: [
    {required: true, message: '请输入新密码！', trigger: 'blur'},
    {min: 6, message: '密码长度至少6位', trigger: 'blur'},
  ],
  reNewPass: [{required: true, message: '请确认新密码！', trigger: 'blur'},
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== passwordForm.newPass) {
          callback(new Error("两次输入不匹配!"))
        } else {
          callback()
        }
      }, trigger: 'blur'
    }
  ],
})
const saveItem = async (formEl: FormInstance | undefined) => {
  if (formEl) {
    const valid = await formEl.validate((valid, fields) => valid);
    if (!valid) return;
  }

  let apiFun, params = {}
  if (dialogFormVisible.value) {
    apiFun = UserApi.updateUserPassword;
    params = {...passwordForm, reNewPass: undefined}
  }
  if (!apiFun) return;
  apiFun({...params}).then((res: any) => {
    if (res.data.status === 1) {
      dialogFormVisible.value && (dialogFormVisible.value = false);
      ElMessage.success(res.data.msg);
      handleCommand('loginout')
    } else {
      ElMessage.error(res.data.msg);
    }
  })
}
// 用户名下拉菜单选择事件
const router = useRouter();
const handleCommand = (command: string) => {
  if (command == 'loginout') {
    user.setUserInfo({});
    cookies.set('pktoken', '')
    router.push('/login');
  } else if (command == 'changePWD') {
    dialogFormVisible.value = true;
    handleEditClear();
  } else if (command == 'user') {
    router.push('/user');
  }
};
</script>
<style scoped>
.header {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: 70px;
  font-size: 22px;
  color: #fff;
}

.collapse-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  float: left;
  padding: 0 21px;
  cursor: pointer;
}

.header .logo {
  float: left;
  width: 250px;
  line-height: 70px;
}

.header-right {
  float: right;
  padding-right: 50px;
}

.header-user-con {
  display: flex;
  height: 70px;
  align-items: center;
}

.btn-fullscreen {
  transform: rotate(45deg);
  margin-right: 5px;
  font-size: 24px;
}

.btn-bell,
.btn-fullscreen {
  position: relative;
  width: 30px;
  height: 30px;
  text-align: center;
  border-radius: 15px;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.btn-bell-badge {
  position: absolute;
  right: 4px;
  top: 0px;
  width: 8px;
  height: 8px;
  border-radius: 4px;
  background: #f56c6c;
  color: #fff;
}

.btn-bell .el-icon-lx-notice {
  color: #fff;
}

.user-name {
  margin-left: 10px;
}

.user-avator {
  margin-left: 20px;
}

.el-dropdown-link {
  color: #fff;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.el-dropdown-menu__item {
  text-align: center;
}
</style>
